package com.myaxuan.controller;

import com.myaxuan.entity.permissions.Menu;
import com.myaxuan.entity.permissions.User;
import com.myaxuan.service.permissions.MenuService;
import com.myaxuan.util.MD5Util;
import com.myaxuan.util.vcode.Captcha;
import com.myaxuan.util.vcode.GifCaptcha;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pc255 on 2018/1/31.
 */

@Controller
public class LoginController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private MenuService menuService;

	private User user;

	/**
	 * 跳转登陆页面
	 * @return
	 */
	@RequestMapping(value="/login",method = RequestMethod.GET)
	public String loginPage(){
		return  "login";
	}

	/**
	 * 跳转后台首页
	 * @return
	 */
	@RequestMapping("/index")
	public String index(){
		return  "index";
	}

	/**
	 * 跳转后台主页
	 * @return
	 */
	@RequestMapping("/main")
	public String main(){
		return  "main/main";
	}

	/**
	 * 被T出后跳转的页面
	 * @return
	 */
	@RequestMapping("/kickout")
	public String kickout(){
		return  "kickout";
	}


	@RequestMapping(value="/dologin",method = RequestMethod.POST)
    public String doLogin(String username,String password,Boolean rememberMe,HttpSession session ,String code ,RedirectAttributes redirectAttributes){
		if(!"true".equals(rememberMe)){
			rememberMe = false;
		}
		//检验验证码,防止暴力破解
		if(!session.getAttribute("_code").toString().equals(code.toLowerCase())){
			logger.info("验证码不对");
			redirectAttributes.addFlashAttribute("message", "验证码不对");
			return "redirect:/login";
		}
		//添加用户认证信息
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
				username,
				MD5Util.toMD5Code(password),
				rememberMe);
		session.setAttribute("username",username);
		//进行验证，这里可以捕获异常，然后返回对应信息
		try {
			subject.login(usernamePasswordToken);
			user=(User) subject.getPrincipal();
			session.setAttribute("user",user);
			logger.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
			return "redirect:/index";
		}  catch (UnknownAccountException uae) {
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
			redirectAttributes.addFlashAttribute("message", "未知账户");
			usernamePasswordToken.clear();
			return "redirect:/login";
		} catch (IncorrectCredentialsException ice) {
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
			redirectAttributes.addFlashAttribute("message", "密码不正确");
			usernamePasswordToken.clear();
			return "redirect:/login";
		} catch (LockedAccountException lae) {
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
			redirectAttributes.addFlashAttribute("message", "账户已锁定");
			usernamePasswordToken.clear();
			return "redirect:/login";
		} catch (ExcessiveAttemptsException eae) {
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
			redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数过多");
			usernamePasswordToken.clear();
			return "redirect:/login";
		} catch (AuthenticationException ae) {
			//通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
			ae.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
			usernamePasswordToken.clear();
			return "redirect:/login";
		}
	}
	/**
	 * 获取验证码（Gif版本）
	 * @param response
	 */
	@RequestMapping(value="getGifCode",method=RequestMethod.GET)
	public void getGifCode(HttpServletResponse response, HttpServletRequest request){
		try {
			HttpSession session = request.getSession(true);
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/gif");
			/**
			 * gif格式动画验证码
			 * 宽，高，位数。
			 */
			Captcha captcha = new GifCaptcha(146,33,4);
			//输出
			captcha.out(response.getOutputStream());

			//存入Session
			System.out.println(captcha.text().toLowerCase());
			session.setAttribute("_code",captcha.text().toLowerCase());
		} catch (Exception e) {
			System.err.println("获取验证码异常："+e.getMessage());
		}
	}
	@RequestMapping(value="menu",method=RequestMethod.GET)
	@ResponseBody
	public List<Menu>  getMenuById(){
		System.out.println("你对象===========================>"+user);
		return menuService.findMenuByUserId(user.getId());
	}
	/**
	 * 退出
	 * @return
	 */
	@RequestMapping(value="logout",method =RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> logout(){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		try {
			//退出
			SecurityUtils.getSubject().logout();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		return resultMap;
	}

}
